import { BNode } from '../type/BNode';
import { IEvent } from '../type/IEvent';
import { TaskState } from '../type/TaskState';

/**
 *  选择树 TODO
 *  根据条件选择执行节点
 */
export class IfElse extends BNode implements IEvent {
    constructor(public rule: boolean, public trueNode?: IEvent, public falseNode?: IEvent) {
        super();
    }

    setRule(rule: boolean) {
        this.rule = rule;
    }

    setTrueNode(node: IEvent) {
        this.trueNode = node;
    }

    setFalseNode(node: IEvent) {
        this.falseNode = node;
    }

    onUpdate(dt: number): void {
        const node = this.check();
        if (!node) {
            return;
        }
        if (node.task.getState() == TaskState.pending) {
            node.task.running();
            node.onStart(this.blackBoard);
        }
        if (node.task.getState() === TaskState.running) {
            node.onUpdate(dt);
        }
        if (node.task.getState() === TaskState.done) {
            this.task.done();
        }
    }

    onCancel(): void {
        const node = this.check();
        if (!node) {
            return;
        }
        node.task.error();
        node.onCancel();
        this.task.error();
    }

    onReset(): void {
        const node = this.check();
        if (!node) {
            return;
        }
        node.task.reset();
        node.onReset();
    }

    onEvent(event: string, data?: any): void {
        const node = this.check();
        if (!node) {
            return;
        }
        node.onEvent(event, data);
    }

    private check() {
        let node: IEvent | undefined;
        if (this.rule) {
            node = this.trueNode;
        } else {
            node = this.falseNode;
        }
        return node;
    }

    getState(): TaskState {
        return this.task.getState();
    }
}
